package io.jenkins.plugins.feishu.service;

import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.nio.charset.StandardCharsets;
import java.util.logging.Logger;

public class FeishuService {
    private static final Logger LOG = Logger.getLogger(FeishuService.class.getName());
    private final String webHookUrl;

    public FeishuService(String webHookUrl) {
        this.webHookUrl = webHookUrl;
    }

    public void send(String color, String title, String content, String jenkinsUrl) throws Exception {
        // 构建卡片消息内容
        String jsonPayload = String.format(
                "{ \"msg_type\": \"interactive\", \"card\": { " + "\"config\": {\"wide_screen_mode\": true}, "
                        + "\"header\": {\"template\":\"%s\", \"title\": {\"tag\": \"plain_text\", \"content\": \"%s\"}}, "
                        + "\"elements\": [{\"tag\": \"markdown\", \"content\": \"%s\"}, "
                        + "{\"tag\":\"action\",\"actions\":[{\"tag\":\"button\",\"text\":{\"tag\":\"plain_text\",\"content\":\"查看日志\"},"
                        + "\"type\":\"primary\",\"multi_url\":{\"url\":\"%s\"}}]}]"
                        + "}}",
                color, title, content, jenkinsUrl);

        // 创建 HttpClient
        HttpClient client = HttpClient.newHttpClient();

        // 创建 POST 请求
        HttpRequest request = HttpRequest.newBuilder()
                .uri(URI.create(webHookUrl))
                .header("Content-Type", "application/json")
                .POST(HttpRequest.BodyPublishers.ofString(jsonPayload, StandardCharsets.UTF_8))
                .build();

        try {
            // 发送请求并获取响应
            HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());
            // 输出响应状态码与响应内容
            LOG.info("发送消息到飞书机器人成功, " + "响应状态码: " + response.statusCode() + "," + "响应内容: " + response.body());
        } catch (Exception e) {
            LOG.warning("发送消息到飞书机器人失败, " + "错误: " + e.getMessage());
            throw e;
        }
    }
}
